<?php
// +----------------------------------------------------------------------
// | title: 标题注释
// +----------------------------------------------------------------------
// | Author: TZ.Leong
// +----------------------------------------------------------------------
// | Date: 2019/7/5 18:08
// +----------------------------------------------------------------------
// | RUN：php think conf mxwh5 single --action getTableItem
// +----------------------------------------------------------------------

namespace app\single\command;


use think\Command;
use think\console\input\Option;
use think\Db;
use think\facade\Cache;

class Conf extends Command
{
    //配置文件目录
    protected $path = "";
    //前端json配置目录
    protected $confPath = "";
    //写文件头部底部
    protected $stringHead = "<?php\n return ";
    protected $stringFooter = ";\n?>";

    protected function configure(){
        parent::configure();
        $this->addOption("action", null, Option::VALUE_OPTIONAL, "action name")
            ->addOption("v", null, Option::VALUE_OPTIONAL, "version");
    }

    /**
     * @param \think\console\Input $input
     * @param \think\console\Output $output
     */
    protected function execute($input, $output)
    {
        //由于数据量比较大，所以要加大内存
        ini_set('memory_limit','2048M');
        $action = $input->getOption("action"); //更新某个配置
        $v = $input->hasOption("v") ? $input->getOption("v") : "";
        $v = $v ?: GAME_NAME;
        $this->confPath = CMF_ROOT . "conf/" . $v . "/";
        $this->path = CMF_ROOT . "data/config/" . $v . "/";
        if (isset($action) && method_exists($this, $action)) {
            $this->$action();
        }else{
            $this->setItemTable();//导入物品配置到表
        }
    }

    /**
     * 更新svn时，执行此方法，从开发服数据库导出数据到文件
     */
    public function getTableItem()
    {
        //生成道具配置
        $itemArr = $this->content("data_item_base");
        $this->write("data_item",$itemArr);
        //生成行为类型配置
        $data = $this->content("data_origin");
        $originArr = array();
        foreach($data as $vo){
            $originArr[$vo["key"]] = $vo["desc"];
        }
        $this->write("origin",$originArr);
        //生成充值类型
        $data = $this->content("data_recharge_type");
        $chargeTypeArr[0] = array("name" => "-=充值道具=-","rmb" => 0);
        foreach($data as $r){
            if($r["class"] == null) continue;
            $chargeTypeArr[$r["class"]] = array(
                "name" => $r["desc"],
                "rmb" => $r["rmb"],
                "show_name" => $r["show_name"] ?? $r["desc"],
                "product_id" => $r["product_id"] ?? ""
            );
        }
        $this->write("recharge_type",$chargeTypeArr);
        //生成充值梯度
        $data = $this->content("data_charge_lv");
        $chargeLvArr = array();
        foreach($data as $r){
            $chargeLvArr[$r["charge_lv"]] = array(
                "name" => $r["charge_lv"],
                "rmb" => $r["charge_lv"],
                "show_name" => $r["show_name"] ?? "儲值".$r["charge_lv"],
                "product_id" => $r["product_id"] ?? ""
            );
        }
        $this->write("recharge_sub_type_1",$chargeLvArr);
        $this->write("recharge_sub_type_2",$chargeLvArr);
        //生成4倍充值档位
        $data = $this->content("data_first_charge_lv");
        if($data){
            $chargeLvArr = array();
            foreach($data as $r){
                $chargeLvArr[$r["first_charge_lv"]] = array(
                    "name" => $r["first_charge_lv"],
                    "rmb" => $r["first_charge_lv"],
                    "show_name" => $r["show_name"] ?? "儲值".$r["first_charge_lv"],
                    "product_id" => $r["product_id"] ?? ""
                );
            }
        }
        $this->write("recharge_sub_type_3",array_slice($chargeLvArr,0,4,true));
        //生成月卡类型
        $data = $this->content("data_vip_monthlycard");
        $monthCardArr = array();
        foreach($data as $r){
            $rmb = $r["price"] ?? 0;
            if($rmb > 0){
                $monthCardArr[$r["type"]] = array(
                    "name" => $r["title_name"],
                    "rmb" => $rmb,
                    "duration" => $r["duration"],
                    "show_name" => $r["show_name"] ?? $r["title_name"],
                    "product_id" => $r["product_id"] ?? ""
                );
            }
        }
        $this->write("recharge_sub_type_4",$monthCardArr);
        //生成RMB直购
        $data = $this->content("data_recharge");
        $rmbBugArr = array();
        foreach($data as $r){
            if($r["type"] == null || empty($r["rmb"])) continue;
            $rmbBugArr[$r["class"]][$r["type"]] = array(
                "name" => $r["title"],
                "rmb" => $r["rmb"],
                "max_num" => $r["num"],
                "switch" => $r["switch"] ?? "",
                "show_name" => $r["show_name"] ?? $r["title"],
                "product_id" => $r["product_id"] ?? ""
            );
        }
        foreach($rmbBugArr as $class => $vo){
            $this->write("recharge_sub_type_".$class, $vo);
        }

        //生成投资购买
        $data = $this->content("data_invest_base");
        $investArr = array();
        foreach($data as $r){
            if(!isset($r["rmb"]) || $r["rmb"] == null) continue;
            $investArr[$r["type"]] = array(
                "name" => $r["desc"],
                "rmb" => $r["rmb"],
                "show_name" => $r["show_name"] ?? $r["desc"],
                "product_id" => $r["product_id"] ?? ""
            );
        }
        $this->write("recharge_sub_type_6", $investArr);
        //生成任务名称配置
        $data = $this->content("data_task_base");
        $taskArr = array();
        foreach($data as $r){
            if(isset($r["type"]) && $r["type"] == 99){
                $taskArr[$r["task_id"]] = $r["task_des"];
            }
        }
        $this->write("task",$taskArr);
        //生成资产配置
        $data = $this->content("data_economy_base");
        $funArr = array();
        foreach($data as $r){
            $funArr[$r["id"]] = array(
                "name" => $r["name"],
                "field" => str_replace("#role_economy.","",$r["record_index"])
            );
        }
        $this->write("data_economy",$funArr);
        //生成研究科技名称配置
        $data = $this->content("data_course_type");
        $funArr = array();
        foreach($data as $r){
            $funArr[$r["id"]] = $r["name"];
        }
        $this->write("course_type",$funArr);
        //生成武将名称配置
        $data = $this->content("data_hero_base");
        $funArr = array();
        foreach($data as $r){
            $funArr[$r["base_id"]] = [
                "name" => $r["name"],
//                "corps" => $r["corps"] ?? 0,
                "star_limit" => $r["star_limit"] ?? 0
            ];
        }
        $this->write("hero",$funArr);
        //生成技能名称配置
        $data = $this->content("data_skill_study");
        $funArr = array();
        foreach($data as $r){
            $funArr[$r["skill_id"]] = $r["name"];
        }
        $this->write("skill_study",$funArr);

        //生成敏感词
        $data = $this->content("data_word");
        $funArr = array();
        foreach($data as $r){
            $funArr[] = $r["keyword"];
        }
        $this->write("word", $funArr);

        //直购diy选择道具
        $data = $this->content("data_recharge_customization");
        $content = [];
        foreach($data as $vo){
            $items = [];
            for($i = 1; $i <= $vo["list_num"]; $i ++){
                if(isset($vo["list".$i])){
                    $itemArr = string2array($vo["list".$i]);
                    foreach($itemArr as $item){
                        $items["list".$i][] = $item[0].",".$item[1];
                    }
                }
            }
            $content[$vo["type"]."-".$vo["sub_type"]] = [
                "max_num" => $vo["list_num"],
                "items" => $items
            ];
        }
        $this->write("recharge_customization", $content);
    }

    /**
     * 生成物品配置，导入表
     */
    public function setItemTable()
    {
        $content = include_once($this->path."data_item.php");
        //需要入库的字段
        $fieldArr = array("code","name","pic","type","sub_type","req_career","req_sex","req_lv","req_round","overlay","quality","desc");
        $addArr = $info = $detailInfo = array();
        //插入数据库，入库前先清理配置表
        $itemModel = Db::table("s_item");
        $itemModel->execute("TRUNCATE TABLE s_item");
        $i = 0;
        //循环拿到的数组对象
        foreach($content as $row){
            $i ++;
            $arr = array();
            if(!isset($row["base_id"])) continue;
            //把对象转成数组形式，方便使用
            $row["code"] = $row["base_id"];
            //获取入库字段的值
            foreach($fieldArr as $key){
                $arr[$key] = (!isset($row[$key]) || empty($row[$key])) ? "" : $row[$key];
            }
            //组装多维数组以便批量入库
            $addArr[] = $arr;
            if($i % 1000 == 0){
                $itemModel->insertAll($addArr);
                $addArr = array();
            }
            //组装code对应的名称，写成文件缓存
            $info[$arr["code"]] = $arr["name"];
            $detailInfo[$row["code"]] = array(
                "name" => $arr["name"],
                "type" => $arr["type"],
                "req_lv" => (int)$arr["req_lv"],
//                "req_round" => (int)$row["req_round"],
            );
        }
        //完整入库
        $addArr && $itemModel->insertAll($addArr);
        //写入文件缓存
        $this->write("item",$info);
        //写入道具详细配置文件缓存
        $this->write("itemDetail",$detailInfo);
    }

    protected function clearCache()
    {
        Cache::clear('admin_menus');
    }

    /**
     * 配置内容
     * @param $fileName
     * @return mixed
     */
    function content($fileName)
    {
        if(is_file($this->confPath.$fileName.".php")){
            return include_once($this->confPath.$fileName.".php");
        }
        return array();
    }

    /**
     * 写入文件
     * @param $fileName
     * @param $content
     */
    function write($fileName,$content)
    {
        $filePath = $this->path.$fileName.".php";
        $dir         =  dirname($filePath);
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        if(file_put_contents($filePath,$this->stringHead.var_export($content, true).$this->stringFooter)){
            echo $filePath." ok!\n";
        }else{
            echo $filePath." error!\n";
        }
    }
}